package Queuedemo;

public class MyQueue {

    //定义双指针的节点的结构
    static class ListNode{
        public int val;
        public ListNode prev;
        public ListNode next;

        public ListNode(int val){//构造方法
            this.val= val;
        }
    }

    //定义两个节点指向双链表的头和尾
    public ListNode head;
    public ListNode last;

    //入队  通过双链表尾插实现
    public void offer(int val){
        ListNode node = new ListNode(val);
        //尾插有两种情况
        //如果头节点本来就是空的,那么last,head,node都指向插入的节点node
        if(head == null){
            head = last = node;
        }else{
            last.next = node;
            node.prev = last;
            last = node;
        }
    }

    //出队 通过双链表头删实现
    // 头删需要考虑三种情况
    public int poll(){
        if(head == null){//1.头为空
            return -1 ;
        }
        int val = -1;//-1表示没有元素
        if(head.next == null) {//2.只有头结点一个节点
            val = head.val;
            head = null;
            last = null;
            return val;
        }//3.多个节点
            val = head.val;
            head = head.next;
            head.prev = null;
            return val;
    }

    public boolean empty(){
        return head == null;
    }

    //获取节点
    public int peek(){
        if(head == null){//1.头为空
            return -1;
        }
        return head.val;
    }

}
